from django.shortcuts import render
from .models import *
from django.http import HttpResponse
from openpyxl import load_workbook,Workbook
# Create your views here.
def index(request):
    ques_type = QuestionType.objects.all()
    content = {'ques_type':ques_type}
    return render(request,'question_bank/account_input.html',content)
def SaveExcel():
    header = ['题型','题目','选项','答案']
    try:
        wb1 = load_workbook('题库.xlsx')
    except FileNotFoundError:
        wb1 = Workbook()
        sheet1 = wb1.active
        sheet1.title = '题库信息'
        for i in range(1,len(header)+1):
            sheet1.cell(row=1,column = i).value = header[i-1]
    finally:
        wb1.save('题库.xlsx')
def Save(request):
    
    info = dict(request.POST)
    quetype = info['question_dtyp'][0]
    question = info['question'][0]
    choice = info['choice'][0]
    answer = info['answer'][0]
    SaveExcel()
    wb2 = load_workbook('题库.xlsx')
    sheet2 = wb2['题库信息']
    row = sheet2.max_row+1
    col = sheet2.max_column +1
    sheet2['A{}'.format(row)].value = quetype
    sheet2['B{}'.format(row)].value = question
    sheet2['C{}'.format(row)].value = choice
    sheet2['D{}'.format(row)].value = answer
    wb2.save('题库.xlsx')
    question_obj = QuestionType.objects.get(question_type=quetype)
    
    que_text = Question.objects.create(quetion_text=question,question_type=question_obj)
    que_text.save()
    if choice =='':
        ans = Answer.objects.create(answer_text=answer, question=que_text)
        ans.save()
    else:
        cho = Choice.objects.create(choice_text=choice, question=que_text)
        cho.save()
        ans = Answer.objects.create(answer_text=answer, question=que_text)
        ans.save()
    
    #context = {'suc':'提交成功！'}
    #return render(request,'gitacc/account_input.html',context)
    return HttpResponse('提交成功')








        
